package com.hmbe.controller;

import com.hmbe.dto.Result;
import com.hmbe.dto.StatusCode;
import com.hmbe.dto.UpdatePwdDTO;
import com.hmbe.entity.HmBeUser;
import com.hmbe.entity.HmBeUserInfo;
import com.hmbe.mapper.HmBeUserInfoMapper;
import com.hmbe.mapper.HmBeUserMapper;
import com.hmbe.service.HmBeUserService;
import com.hmbe.utils.GetUserUtils;
import com.hmbe.utils.MinIOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/my")
public class HmBeUserController {

    @Autowired
    private HmBeUserService userService;
    @Autowired
    private HmBeUserInfoMapper hmBeUserInfoMapper;
    @Autowired
    private HmBeUserMapper HmBeUserMapper;
    @Autowired
    private MinIOUtils minIOUtils;

    @GetMapping("/userinfo")
    public Result getUserInfo(HttpServletRequest httpServletRequest) {
        return userService.getUserInfo(httpServletRequest);
    }

    @PutMapping("/userinfo")
    public Result updateUserInfo(@RequestBody HmBeUserInfo userInfo, HttpServletRequest httpServletRequest) {
        System.out.println("userInfo = " + userInfo);
        return userService.updateUserInfo(userInfo, httpServletRequest);
        //return Result.ok("更新用户信息成功！", StatusCode.SUCCESS);
    }

    @PostMapping("/update/avatar")
    public Result updateUserInfo(@RequestParam("avatar") MultipartFile avatar,
                                 @RequestParam("userId") Long userId) {

        String url = null;
        try {
            //1.删除原来的头像
            minIOUtils.deleteFile("default-bucket", "my");
            minIOUtils.uploadFile("default-bucket", "my", avatar);
            url = minIOUtils.getPresignedObjectUrl("default-bucket", "my", 7);
            HmBeUserInfo hmBeUserInfo = hmBeUserInfoMapper.selectById(userId);
            hmBeUserInfo.setUserPic(url);
            hmBeUserInfoMapper.updateById(hmBeUserInfo);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.ok("更新用户头像成功！", StatusCode.SUCCESS);
    }

    @PostMapping("/updatepwd")
    public Result updatePwd(@RequestBody UpdatePwdDTO updatePwdDTO, HttpServletRequest request) {
        System.out.println("hmBeUser = " + updatePwdDTO);
        Long userId = GetUserUtils.getUserId(request);
        HmBeUser hmBeUser = HmBeUserMapper.selectById(userId);
        hmBeUser.setPassword(updatePwdDTO.getNewPwd());
        hmBeUser.setRepassword(updatePwdDTO.getRePwd());
        HmBeUserMapper.updateById(hmBeUser);
        return Result.ok("更新用密码像成功！", StatusCode.SUCCESS);
    }

}
